package com.xul.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xul.common.exception.Assert;
import com.xul.common.result.ResponseEnum;
import com.xul.srb.base.dto.SmsDTO;
import com.xul.srb.base.uitl.JwtUtils;
import com.xul.srb.core.enums.TransTypeEnum;
import com.xul.srb.core.hfb.FormHelper;
import com.xul.srb.core.hfb.HfbConst;
import com.xul.srb.core.hfb.RequestHelper;
import com.xul.srb.core.mapper.TransFlowMapper;
import com.xul.srb.core.mapper.UserAccountMapper;
import com.xul.srb.core.mapper.UserInfoMapper;
import com.xul.srb.core.pojo.bo.TransFlowBO;
import com.xul.srb.core.pojo.entity.TransFlow;
import com.xul.srb.core.pojo.entity.UserAccount;
import com.xul.srb.core.pojo.entity.UserInfo;
import com.xul.srb.core.service.TransFlowService;
import com.xul.srb.core.service.UserAccountService;
import com.xul.srb.core.service.UserInfoService;
import com.xul.srb.core.util.LendNoUtils;
import com.xul.srb.rabbitmq.Service.MQService;
import com.xul.srb.rabbitmq.constant.MQConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author xul
 * @since 2021-11-06
 */
@Service
@Slf4j
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private TransFlowService transFlowService;

    @Resource
    private TransFlowMapper transFlowMapper;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private MQService mqService;

    /**
     * 充值
     *
     * @param chargeAmt
     * @param request
     * @return
     */
    @Override
    public String commitCharge(BigDecimal chargeAmt, HttpServletRequest request) {

        Long userId = JwtUtils.getUserId(request.getHeader("token"));
        UserInfo userInfo = userInfoMapper.selectById(userId);

        Map<String, Object> paramMap = new HashMap<>();
        // 给商户分配的唯一标识
        paramMap.put("agentId", HfbConst.AGENT_ID);
        // 充值交易号
        paramMap.put("agentBillNo", LendNoUtils.getNo());
        // 绑定code
        paramMap.put("bindCode", userInfo.getBindCode());
        // 充值金额
        paramMap.put("chargeAmt", chargeAmt);
        // 手续费
        paramMap.put("feeAmt", new BigDecimal("0"));
        // 充值异步回调 http://localhost/api/core/userAccount/notify
        paramMap.put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL);
        // 充值同步回调 http://localhost:3000/user
        paramMap.put("returnUrl", HfbConst.RECHARGE_RETURN_URL);
        // 时间搓
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        // 加密签名
        paramMap.put("sign", RequestHelper.getSign(paramMap));

        // 构建充值自动提交表单 http://localhost:9999/userAccount/AgreeBankCharge
        return FormHelper.buildForm(HfbConst.RECHARGE_URL, paramMap);
    }

    /**
     * 用户充值异步回调 处理返回的数据
     *
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String notifyMap(Map<String, Object> map) {

        // 获取充值绑定协议号
        String bindCode = (String) map.get("bindCode");
        // 获取充值金额
        String chargeAmt = (String) map.get("chargeAmt");
        // 获取流水号
        String agentBillNo = (String) map.get("agentBillNo");

        // 处理幂等性问题
        QueryWrapper<TransFlow> wrapper = new QueryWrapper<>();
        wrapper.eq("trans_no", agentBillNo);
        Integer integer = transFlowMapper.selectCount(wrapper);
        if (integer > 0) {
            log.info("幂等性返回");
            return "success";
        }

        // 将账户金额同步到数据库
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("bind_code", bindCode));
        userAccountMapper.updateAccount(userInfo.getId(), chargeAmt, new BigDecimal(0));

        // 将用户每笔流水存入流水表
        TransFlowBO transFlowBO = new TransFlowBO(agentBillNo, bindCode, new BigDecimal(chargeAmt), TransTypeEnum.RECHARGE, "会员充值");
        transFlowService.insertTransFlow(transFlowBO);

        // rabbitmq 发消息
        log.info("发消息");
        String mobile = userInfoService.getMobileByBindCode(bindCode);
        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setMobile(mobile);
        smsDTO.setMessage("充值成功");
        mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS, MQConst.ROUTING_SMS_ITEM, smsDTO);

        return "success";
    }

    /**
     * 查询账户余额
     *
     * @param request
     * @return
     */
    @Override
    public BigDecimal getAccount(HttpServletRequest request) {
        Long userId = JwtUtils.getUserId(request.getHeader("token"));
        UserAccount userAccount = baseMapper.selectOne(new QueryWrapper<UserAccount>().eq("user_id", userId));
        return userAccount.getAmount();
    }

    /**
     * 用户提现
     *
     * @param fetchAmt
     * @param userId
     * @return
     */
    @Override
    public String commitWithdraw(BigDecimal fetchAmt, Long userId) {

        // 账户可用余额充足：当前用户的余额 >= 当前用户的提现金额
        UserAccount userAccount = baseMapper.selectOne(new QueryWrapper<UserAccount>().eq("user_id", userId));
        BigDecimal amount = userAccount.getAmount();
        Assert.isTrue(amount.intValue() >= fetchAmt.doubleValue(), ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);

        UserInfo userInfo = userInfoMapper.selectById(userId);
        String bindCode = userInfo.getBindCode();
        // 组装表单提交数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentBillNo", LendNoUtils.getWithdrawNo());
        paramMap.put("bindCode", bindCode);
        paramMap.put("fetchAmt", fetchAmt);
        paramMap.put("feeAmt", new BigDecimal(0));
        paramMap.put("notifyUrl", HfbConst.WITHDRAW_NOTIFY_URL);
        paramMap.put("returnUrl", HfbConst.WITHDRAW_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);

        String formStr = FormHelper.buildForm(HfbConst.WITHDRAW_URL, paramMap);

        return formStr;
    }

    /**
     * 提现成功交易
     *
     * @param paramMap
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void notifyWithdraw(Map<String, Object> paramMap) {

        String agentBillNo = (String) paramMap.get("agentBillNo");
        QueryWrapper<TransFlow> wrapper = new QueryWrapper<>();
        wrapper.eq("trans_no", agentBillNo);
        TransFlow transFlow = transFlowMapper.selectOne(wrapper);
        if (transFlow != null) {
            log.warn("幂等性返回");
            log.warn("幂等性返回");
            return;
        }

        String bindCode = (String) paramMap.get("bindCode");
        String fetchAmt = (String) paramMap.get("fetchAmt");

        // 修改账户金额
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("bind_code", bindCode));
        baseMapper.updateAccountLend(userInfo.getId(), new BigDecimal(fetchAmt).negate(), new BigDecimal(0));

        //增加交易流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(fetchAmt),
                TransTypeEnum.WITHDRAW,
                "提现");
        transFlowService.insertTransFlow(transFlowBO);
    }
}
